package com.xzcs.quartz;

import com.xzcs.mapper.sequence.SequenceMapper;
import com.xzcs.mapper.task.QuartzTaskMapper;
import com.xzcs.util.common.DateUtils;
import com.xzcs.util.common.StringUtils;
import com.xzcs.util.spring.PropertyUtils;
import org.quartz.Job;
import org.quartz.JobDataMap;
import org.quartz.JobExecutionContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.HashMap;
import java.util.Map;

public class BaseJob implements Job {
	
	public final Logger logger = LoggerFactory.getLogger(this.getClass());
	@Autowired
	public PropertyUtils propertyUtils;
	@Autowired
	private SequenceMapper sequenceMapper;
	@Autowired
	private QuartzTaskMapper quartzTaskMapper;

	@Override
	public void execute(JobExecutionContext jobexc) {
		String logId = DateUtils.getToday("yyyyMMddHHmmss") + sequenceMapper.getSequenceValue("seq_log_id");
		//获取job参数信息
        JobDataMap dataMap = jobexc.getJobDetail().getJobDataMap();
		String taskId = StringUtils.get(dataMap, "taskId");
        String taskClass = StringUtils.get(dataMap, "taskClass");//运行类
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("logId", logId);
		params.put("taskId", taskId);
		params.put("status", "1");
		params.put("runMsg", "运行中");
		quartzTaskMapper.insertQuartzTaskLog(params);

        try {
        	JobTask jobTask = (JobTask)Class.forName(taskClass).newInstance();
        	jobTask.run(propertyUtils);
			params.put("status", "2");
			params.put("runMsg", "运行成功");
		} catch (Exception e) {
			logger.debug("任务执行失败：", e);
			params.put("status", "3");
			params.put("runMsg", "运行失败："+e.getMessage());
		}

		logger.debug(taskClass+"执行完毕...");
		quartzTaskMapper.updateQuartzTaskLog(params);
	}
}
